package com.MRSyc.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.MRSyc.base.BaseController;
import com.MRSyc.config.MrConfig;
import com.MRSyc.config.PageModel;
import com.MRSyc.entity.FError;
import com.MRSyc.entity.ICStockBill;
import com.MRSyc.entity.ICStockBillVo;
import com.MRSyc.entity.InboundDocument;
import com.MRSyc.entity.OutboundDocument;
import com.MRSyc.entity.OutboundDocumentEntry;
import com.MRSyc.entity.Pagination;
import com.MRSyc.entity.ReagentInboundDocument;
import com.MRSyc.entity.ReagentInboundDocumentVo;
import com.MRSyc.entity.TOutResult;
import com.MRSyc.entity.TUdiCode;
import com.MRSyc.mapper.ICStockBillEntryMapper;
import com.MRSyc.mapper.ICStockBillMapper;
import com.MRSyc.mapper.TOutResultMapper;
import com.MRSyc.utils.ClientUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Fxq
 * @since 2021-01-29
 */
@Controller
@RequestMapping(value = "/")
public class ICStockBillController extends BaseController {

	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	private ClientUtils client = new ClientUtils();

	@Autowired
	ICStockBillMapper icMapper;

	@Autowired
	ICStockBillEntryMapper icEntryMapper;

	@Autowired
	private MrConfig mrconfig;

	@Autowired
	TOutResultMapper outMapper;

	@RequestMapping(value = "/sales/list", method = RequestMethod.GET)
	public String sales_list() {

		return "sales/sales_list";
	}

	@RequestMapping(value = "/sales/list", method = RequestMethod.POST)
	@ResponseBody
	public PageModel searchSales_list(PageModel<OutboundDocument> page, ICStockBillVo v) {
		page.init();

		if (v.getFDate() != null) {
			IPage<OutboundDocument> ipage = new Page<OutboundDocument>();
			ipage.setCurrent(1);
			ipage.setSize(100);
			QueryWrapper<OutboundDocument> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("t1.FTranType", 21);
			queryWrapper.eq("t1.FROB", 1);
			queryWrapper.like("t3.FFullName", "迈瑞");
			queryWrapper.like("t3.FFullName", "试剂");
			queryWrapper.notExists("select * from t_out_result t where t1.FBillNo=t.FBillNo");
			if (v.getFDate() != null)
				queryWrapper.ge("t1.fdate", v.getFDate());
			if (v.getFCheckDate() != null)
				queryWrapper.le("t1.fdate", v.getFCheckDate());
			if (v.getFBillNo() != null)
				queryWrapper.like("t1.FBillNo", v.getFBillNo());
			if (v.getFName() != null)
				queryWrapper.like("t4.FName", v.getFName());
			if (v.getFTaxNum() != null)
				queryWrapper.like("t4.FTaxNum", v.getFTaxNum());
			IPage<OutboundDocument> list = icMapper.selectOutList(ipage, queryWrapper);
			page.packData(0, list.getRecords());
		} else {
			page.packData(0, new ArrayList<>());
		}

		return page;
	}

	/*
	 * 试剂出库单查询
	 */

	@RequestMapping(value = "/sales/outboundDocumentsSearch", method = RequestMethod.GET)
	public String outboundDocuments_list() {

		return "sales/outboundDocuments_list";
	}

	@RequestMapping(value = "/sales/outboundDocumentsSearch", method = RequestMethod.POST)
	@ResponseBody
	public PageModel outboundDocumentsSearch_list(PageModel<ReagentInboundDocumentVo> page, ICStockBillVo v) {
		page.init();
		Map<String, String> params = new HashMap<>();
		params.put("documentType", "SalesOutbound");
		params.put("currentPage", "0");
		params.put("pageSize", "100");
		if (v.getFDate() != null) {
			params.put("startDate", format.format(v.getFDate()));
		} else {
			return page;
		}
		if (v.getFCheckDate() != null)
			params.put("endDate", format.format(v.getFCheckDate()));
		if (StringUtils.isNotEmpty(v.getFBillNo()))
			params.put("documentNumber", v.getFBillNo());
		if (StringUtils.isNotEmpty(v.getFName()))
			params.put("status", v.getFName());
		Map<String, Object> map = getOutboundList(params);
		List<ReagentInboundDocument> reagentInboundDocumentList = new ArrayList<>();
		List<ReagentInboundDocumentVo> reagentInboundDocumentVoList = new ArrayList<>();
		Pagination pagination = new Pagination();
		Object code = map.get("code");
		if (code != null) {
			switch (code.toString()) {
			case "200":
				Object result = map.get("result");
				System.out.println("result1 :" + result.toString());
				reagentInboundDocumentList = parseReagentInboundDocumentList(result);
				reagentInboundDocumentVoList = changeData(reagentInboundDocumentList, reagentInboundDocumentVoList);
				pagination = parsePagination(result);
				break;
			case "401":
				// 未授权或授权到期重新授权
				Map<String, String> param = new HashMap<>();
				param.put("client_id", mrconfig.getClient_id());
				param.put("client_secret", mrconfig.getClient_secret());
				param.put("grant_type", mrconfig.getGrant_type());
				param.put("username", mrconfig.getUsername());
				param.put("password", mrconfig.getPassword());
				client.getToken(mrconfig.getLoginUrl(), param);
				// if(token!=null) param.put("Authorization", "Bearer "+token);
				map = getOutboundList(params);
				code = map.get("code");
				if (code != null) {
					switch (code.toString()) {
					case "200":
						result = map.get("result");

						reagentInboundDocumentList = parseReagentInboundDocumentList(result);
						reagentInboundDocumentVoList = changeData(reagentInboundDocumentList,
								reagentInboundDocumentVoList);
						System.out.println("result2 :" + result.toString());
						pagination = parsePagination(result);
						break;
					}
				}
				break;
			case "403":
				break;
			case "404":
				break;
			}

			page.packData(0, reagentInboundDocumentVoList);
		} else {
			page.packData(0, new ArrayList<>());
		}
		return page;
	}

	public Map<String, Object> getOutboundList(Map<String, String> params) {
		return client.getInboundList(mrconfig.getOutboundUrl(), params);
	}

	@RequestMapping(value = "/sales/createDocuments", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> createDocuments(@RequestBody Map<String, String> m) {
		// List<ReagentInboundDocument> reagentInboundDocumentList =
		// JSON.parseArray(recordList, ReagentInboundDocument.class);
		System.out.println("createDocuments....");
		Map<String, Object> map = new HashMap<>();

		try {

			// List<FError> errors=new ArrayList<>();
			QueryWrapper<OutboundDocument> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("t1.FTranType", 21);
			queryWrapper.eq("t1.FROB", 1);
			queryWrapper.like("t3.FFullName", "迈瑞");
			queryWrapper.like("t3.FFullName", "试剂");
			if (m.get("FDate") != null)
				queryWrapper.ge("t1.fdate", m.get("FDate"));
			if (m.get("FCheckDate") != null)
				queryWrapper.le("t1.fdate", m.get("FCheckDate"));
			if (m.get("FBillNo") != null)
				queryWrapper.like("t1.FBillNo", m.get("FBillNo"));
			if (m.get("FName") != null)
				queryWrapper.like("t4.FName", m.get("FName"));
			if (m.get("FTaxNum") != null)
				queryWrapper.like("t4.FTaxNum", m.get("FTaxNum"));
			queryWrapper.notExists("select * from t_out_result t where t1.FBillNo=t.FBillNo");
			List<ICStockBill> list = icMapper.selectICStockBillList(queryWrapper);
			map = createDocumentHead(list);
			/*
			 * map.put("code", 200); map.put("error", errors);
			 */

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 500);
		}

		return map;

	}

	/*
	 * 创建出库单
	 */
	public Map<String, Object> createDocumentHead(List<ICStockBill> list) {
		Map<String, Object> response = new HashMap<>();
		List<FError> errs = new ArrayList<>();
		SimpleDateFormat f=new SimpleDateFormat("yyyyMMdd HH:mm:ss");
		for (ICStockBill b : list) {
			String json = "{";
			OutboundDocument doc = icMapper.selectByFInterid(b.getFInterID());
			if (doc != null) {
				json += "\"creationTime\": \"" + f.format(doc.getFDate()) + "\",";
				// json +="\"clientID\": \""+doc.getFTaxNum()+"\",";
				String clientID="12510000450756139Y";
				
				json += "\"deliveryDate\": \"" + f.format(doc.getFDate()) + "\",";
				json += "\"documentType\": \"SalesOutbound\",";
				json += "\"phoneNOOfSalesPerson\": \"" + mrconfig.getUsername() + "\",";
				json += "\"salesPerson\": \""+doc.getFSalesPerson()+"\",";
				/*json += "\"b2bUnitName\": \"" + doc.getFSupname() + "\",";
				json += "\"province\": \"170\",";
				json += "\"city\": \"WH\",";
				json += "\"county\": \"WH1\",";
				json += "\"detailedAddress\": \"武汉市江岸区\",";*/
				/*
				 * json +="\"city\": \"武汉市\","; json +="\"county\": \"武昌区\","; json
				 * +="\"province\": \"省\",";
				 */
				String b2bUnitName=doc.getFSupname();
				if(StringUtils.isNotEmpty(doc.getFSupNumber())) {
					if(!doc.getFSupNumber().startsWith("01")) {
						//b2bUnitName，province，city，county，detailedAddress
						String code=doc.getFSupAddCode();
						if(StringUtils.isNotEmpty(code)) {
							String[] arrs=code.split("-");
							if(arrs.length==3) {
								
								json += "\"province\": \"" + arrs[0] + "\",";
								json += "\"city\": \"" + arrs[1] + "\",";
								json += "\"county\": \"" + arrs[2] + "\",";
								json += "\"detailedAddress\": \"" + doc.getFAddress() + "\",";
								if(StringUtils.isEmpty(doc.getFTaxNum())) {
									clientID="111111111111111111";
									b2bUnitName="二级渠道试剂备货(DMS)专用";
								}
								json += "\"b2bUnitName\": \"" + b2bUnitName + "\",";
								json +="\"contactPerson\": \"" + doc.getFContact() + "\",";
								json +="\"phoneNumber\": \"" + doc.getFPhone() + "\",";
							}
						}
						
					}
				}
				
				json += "\"clientID\": \""+clientID+"\",";
			}
			List<OutboundDocumentEntry> entrys = icMapper.getDocumentEntrys(b.getFInterID());
			if (entrys != null && entrys.size() > 0) {
				json += "\"reagentOutboundDocumentEntries\": [";
				
				for (OutboundDocumentEntry entry : entrys) {
					BigDecimal bd = new BigDecimal(entry.getPrice());
					BigDecimal bq = new BigDecimal(entry.getQuantity());
					float price = bd.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
					float qty = bq.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
					json += "{";
					json += "\"batchNumber\": \"" + entry.getBatchNumber() + "\",";
					//json += "\"batchNumber\": \"2019120100\",";
					json += "\"entryNumber\": \"" + entry.getEntryNumber() + "0\",";
					json += "\"materialNumber\": \"" + entry.getMaterialNumber() + "\",";
					json += "\"price\": \"" + price + "\",";
					json += "\"quantity\": \"" + Math.round(qty) + "\",";
					json += "\"salesUnitCode\": \"" + entry.getSalesUnitCode() + "\",";
					List<TUdiCode> udiCodes = icMapper.getUdiCodes(b.getFInterID(), entry.getMaterialNumber());
					if (udiCodes != null && udiCodes.size() > 0) {
						json += "";
					}
					json += "\"salesUnitDesc\": \"" + entry.getSalesUnitDesc() + "\"";
					json += "},";

				}
				json = json.substring(0, json.length() - 1);
				 

				/*float price = 99.99f;
				json += "{";
				json += "\"batchNumber\": \"2019122312\",";
				json += "\"entryNumber\": \"10\",";
				json += "\"materialNumber\": \"105-001951-00\",";
				json += "\"price\": \"" + price + "\",";
				json += "\"quantity\": \"1\",";
				json += "\"salesUnitCode\": \"KSR\",";

				json += "\"salesUnitDesc\": \"箱\"";
				json += "},";
				
				json += "{";
				json += "\"batchNumber\": \"2019122411\",";
				json += "\"entryNumber\": \"20\",";
				json += "\"materialNumber\": \"105-001957-00\",";
				json += "\"price\": \"" + price + "\",";
				json += "\"quantity\": \"1\",";
				json += "\"salesUnitCode\": \"KSR\",";

				json += "\"salesUnitDesc\": \"箱\"";
				json += "}";*/

				json += "]";

			}
			json += "}";
			// if(doc!=null&&doc.getFPhoneNOOfSalesPerson()!=null) {
			System.out.println(json);
			// }

			Map<String, Object> map = createOutDocuments(json);
			Object code = map.get("code");
			if (code != null) {
				switch (code.toString()) {
				case "200":
					Object result = map.get("result");
					System.out.println("result1 :" + result.toString());

					break;
				case "401":
					// 未授权或授权到期重新授权
					Map<String, String> param = new HashMap<>();
					param.put("client_id", mrconfig.getClient_id());
					param.put("client_secret", mrconfig.getClient_secret());
					param.put("grant_type", mrconfig.getGrant_type());
					param.put("username", mrconfig.getUsername());
					param.put("password", mrconfig.getPassword());
					client.getToken(mrconfig.getLoginUrl(), param);
					// if(token!=null) param.put("Authorization", "Bearer "+token);
					map = createOutDocuments(json);
					break;
				case "403":
					break;
				case "404":
					break;
				}
			}
			FError err = new FError();
			err.setFcode(map.get("code").toString());
			err.setDesc(map.get("result").toString());
			err.setFname(doc.getFBillNo());
			err.setDesc("创建成功！");
			if ("200".equals(map.get("code").toString())) {
				int maxId = icMapper.getMaxId();
				TOutResult result = new TOutResult();
				result.setId(maxId);
				result.setFBillNo(doc.getFBillNo());
				result.setFoutNumber(map.get("result").toString());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				result.setFCreatedate(format.format(new Date()));
				outMapper.insert(result);
				/*
				 * b.setFis_create(1); b.setFfout_number(map.get("result").toString());
				 * icMapper.updateById(b);
				 */
			} else {
				err.setDesc("创建失败：" + map.get("result").toString());
			}
			errs.add(err);

			System.out.println(map.toString());
			break;

		}
		response.put("code", 200);
		response.put("errs", errs);
		return response;

	}

	public Map<String, Object> createOutDocuments(String json) {
		Map<String, String> params = new HashMap<>();
		params.put("json", json);
		return client.createOutboundList(mrconfig.getCreateUrl(), params);
	}

	/*
	 * 解析迈瑞接口返回的出库列表信息
	 */
	public List<ReagentInboundDocument> parseReagentInboundDocumentList(Object result) {
		List<ReagentInboundDocument> list = new ArrayList<>();
		JSONObject obj = JSONObject.parseObject(result.toString());
		if (obj != null) {
			JSONArray documents = obj.getJSONArray("documents");
			if (documents != null && documents.size() > 0) {
				for (int i = 0; i < documents.size(); i++) {
					JSONObject head = documents.getJSONObject(i);
					list.add(parseReagentInboundDocument(head));
				}
			}
		}
		return list;
	}

	public ReagentInboundDocument parseReagentInboundDocument(JSONObject head) {
		ReagentInboundDocument document = new ReagentInboundDocument();
		if (head != null) {
			String b2bUnit = head.getString("b2bUnit");
			String b2bUnitName = head.getString("b2bUnitName");
			String clientID = head.getString("clientID");
			String clientName = head.getString("clientName");
			String contactPerson = head.getString("contactPerson");
			String creationTime = head.getString("creationTime");
			String documentNo = head.getString("documentNo");
			String documentType = head.getString("documentType");
			String documentTypeDesc = head.getString("documentTypeDesc");
			String externalOrderNo = head.getString("externalOrderNo");
			String lender = head.getString("lender");
			String phoneNOOfSalesPerson = head.getString("phoneNOOfSalesPerson");
			String phoneNumber = head.getString("phoneNumber");
			String returnReason = head.getString("returnReason");
			String salesPerson = head.getString("salesPerson");
			String status = head.getString("status");

			JSONArray bodys = head.getJSONArray("reagentOutboundDocumentEntries");
			List<InboundDocument> list = new ArrayList<>();
			if (bodys != null && bodys.size() > 0) {
				for (int j = 0; j < bodys.size(); j++) {
					JSONObject body = bodys.getJSONObject(j);
					list.add(parseInboundDocument(body));
				}
			}
			document.setB2bUnit(b2bUnit);
			document.setB2bUnitName(b2bUnitName);
			document.setClientID(clientID);
			document.setClientName(clientName);
			document.setContactPerson(contactPerson);
			document.setCreationTime(creationTime);
			document.setDocumentNo(documentNo);
			document.setDocumentType(documentType);
			document.setDocumentTypeDesc(documentTypeDesc);
			document.setExternalOrderNo(externalOrderNo);
			document.setInboundDocumentList(list);
			document.setLender(lender);
			document.setPhoneNOOfSalesPerson(phoneNOOfSalesPerson);
			document.setPhoneNumber(phoneNumber);
			document.setReturnReason(returnReason);
			document.setSalesPerson(salesPerson);
			document.setStatus(status);

		}
		return document;
	}

	public InboundDocument parseInboundDocument(JSONObject body) {
		InboundDocument document = new InboundDocument();
		if (body != null) {
			String batchNumber = body.getString("batchNumber");
			String dueDate = body.getString("dueDate");
			String entryNumber = body.getString("entryNumber");
			String materialDesc = body.getString("materialDesc");
			String materialNumber = body.getString("materialNumber");
			String orderEntryNumber = body.getString("orderEntryNumber");
			String productionDate = body.getString("productionDate");
			String quantity = body.getString("completedQuantity");
			String salesUnitCode = body.getString("salesUnitCode");
			String salesUnitDesc = body.getString("salesUnitDesc");
			String documentNo = body.getString("documentNo");
			JSONArray udiCodeList = body.getJSONArray("completedOutboundUdiList");
			List<TUdiCode> udiCodes = new ArrayList<>();
			if (udiCodeList != null && udiCodeList.size() > 0) {
				for (int m = 0; m < udiCodeList.size(); m++) {
					JSONObject udiCode = udiCodeList.getJSONObject(m);
					udiCodes.add(parseUdiCode(udiCode));
				}
			}
			document.setBatchNumber(batchNumber);
			document.setDocumentNo(documentNo);
			document.setDueDate(dueDate);
			document.setEntryNumber(entryNumber);
			document.setMaterialDesc(materialDesc);
			document.setMaterialNumber(materialNumber);
			document.setOrderEntryNumber(orderEntryNumber);
			document.setProductionDate(productionDate);
			document.setQuantity(quantity);
			document.setSalesUnitCode(salesUnitCode);
			document.setSalesUnitDesc(salesUnitDesc);
			document.setUdiCodeList(udiCodes);
		}
		return document;
	}

	public TUdiCode parseUdiCode(JSONObject udiCode) {
		TUdiCode u = new TUdiCode();

		if (udiCode != null) {
			String dueDate = udiCode.getString("dueDate");
			String materialNumber = udiCode.getString("materialNumber");
			String productUniName = udiCode.getString("productUniName");
			String productionDate = udiCode.getString("productionDate");
			String trackingCode = udiCode.getString("trackingCode");
			// String unit = udiCode.getString("unit");
			u.setFduedate(dueDate);
			u.setFmaterialNumber(materialNumber);
			u.setFproductionDate(productionDate);
			u.setFproductUniName(productUniName);
			u.setFtrackingCode(trackingCode);
		}
		return u;
	}

	public Pagination parsePagination(Object result) {
		Pagination pagination = new Pagination();
		JSONObject json = JSONObject.parseObject(result.toString());
		if (json != null) {
			JSONObject page = json.getJSONObject("pagination");
			if (page != null) {
				int currentPage = page.getInteger("page");
				int pageSize = page.getInteger("count");
				String sort = page.getString("sort");
				int totalPages = page.getInteger("totalPages");
				int totalResults = page.getInteger("totalCount");
				pagination.setCurrentPage(currentPage);
				pagination.setPageSize(pageSize);
				pagination.setSort(sort);
				pagination.setTotalPages(totalPages);
				pagination.setTotalResults(totalResults);
			}
		}

		return pagination;
	}

	public List<ReagentInboundDocumentVo> changeData(List<ReagentInboundDocument> reagentInboundDocumentList,
			List<ReagentInboundDocumentVo> reagentInboundDocumentVoList) {
		for (ReagentInboundDocument d : reagentInboundDocumentList) {
			List<InboundDocument> arrs = d.getInboundDocumentList();
			for (InboundDocument in : arrs) {
				ReagentInboundDocumentVo v = new ReagentInboundDocumentVo();
				v.setB2bUnit(d.getB2bUnit());
				v.setCreationTime(d.getCreationTime());
				v.setDocumentNo(d.getDocumentNo());
				v.setDocumentType(d.getDocumentType());
				v.setDocumentTypeDesc(d.getDocumentTypeDesc());
				v.setExternalOrderNo(d.getExternalOrderNo());
				v.setBatchNumber(in.getBatchNumber());
				v.setDueDate(in.getDueDate());
				v.setEntryNumber(in.getEntryNumber());
				v.setMaterialNumber(in.getMaterialNumber());
				v.setMaterialDesc(in.getMaterialDesc());
				v.setProductionDate(in.getProductionDate());
				v.setQuantity(in.getQuantity());
				v.setSalesUnitCode(in.getSalesUnitCode());
				v.setSalesUnitDesc(in.getSalesUnitDesc());
				v.setInboundDocumentList(d.getInboundDocumentList());
				reagentInboundDocumentVoList.add(v);
			}
		}
		return reagentInboundDocumentVoList;
	}

}
